package com.common.activity.adapter;

import java.util.ArrayList;

import uk.co.senab.photoview.PhotoView;
import android.app.Activity;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.common.android.ui.gif.GifImageView;
import com.common.weibolib.GlobalSetting;
import com.common.weibolib.Image;
import com.common.weibolib.ImageList;
import com.common.weibolib.PictureHolderForWeibo;
import com.product.android.ui.imageHolder.CircleProgress;
import com.product.android.utils.SaveTweetImageTask;
import com.starappallcommon.R;

/**
 * 外面使用的界面销毁后一定要调用这里的Destroy()，用来停止GIF线程 ClassName:TweetFlowImageAdapter
 * 
 * <br>
 * Created 2014-5-16 下午12:08:52
 * 
 * @version
 * @author 黄永鑫,HuangYK
 * 
 * @see
 */
public class TweetFlowImageAdapter extends PagerAdapter implements
		OnClickListener {

	private ImageList mImgList = new ImageList();// 所有图片的URL地址
	private ArrayList<PictureHolderForWeibo> mHolderList = new ArrayList<PictureHolderForWeibo>();
//	private TopicInfo mTopic = null;// 微博
	private Context mContext = null;
	public boolean mIsLike = false;
//	private LikeAsyncTask mLikeTask;
	private int mleftBtnResId;//左边按钮的图片id
	private int mRightBtnResId;//右边按钮的图片id
	private OnClickListener mLeftBtnListener;
	private OnClickListener mRightBtnListener;
	
	private boolean isLocalImage=false;
	private boolean isPraised=false;
	private boolean isCanPraised=false;
	private int praises=0;

	/**
	 * 显示大图
	 * Creates a new instance of TweetFlowImageAdapter.
	 * <br>Created 2014-8-6 下午5:03:23
	 * @param context 上下文句柄
	 * @param sources 图片路径，可以是本地图片。
	 * @param isLocalImage 是否是本地图片。
	 * @param isPraised 是否已经点赞
	 * @param praises 赞的数量
	 * @param isCanPraised 是否可以点击赞。
	 */
	public TweetFlowImageAdapter(Context context, ArrayList<String> sources,
			boolean isLocalImage,boolean isPraised,int praises,boolean isCanPraised) {
		if (null == sources||sources.isEmpty()) {
			return;
		}
		this.isLocalImage=isLocalImage;
		this.isPraised=isPraised;
		this.isCanPraised=isCanPraised;
		this.praises=praises;
		
		setSources(sources);
		mContext = context;
	}

	@Override
	public int getCount() {
		return mImgList.size();
	}

	/**
	 * 设置源数据
	 * 
	 * <br>Created 2014-6-9 下午5:57:57
	 * @param sources 图片列表
	 * @author        :  HuangYK
	 */
	public void setSources(ArrayList<String> sources) {
		if (null == sources || sources.isEmpty()) {
			return;
		}
		mImgList.clear();
		for (int i = 0; i < sources.size(); i++) {
			Image image = new Image();
			image.image_original = sources.get(i);
			image.image_thumb = image.image_original;
			mImgList.add(image);
		}
	}

	/**
	 * 获取item
	 * 
	 * <br>Created 2014-6-9 下午5:58:30
	 * @param position 索引
	 * @return Object
	 * @author        :  HuangYK
	 */
	public Object getItem(int position) {
		if (position < mImgList.size()) {
			return mImgList.get(position);
		} else {
			return null;
		}
	}

	/**
	 * 设置赞数量
	 * 
	 * <br>Created 2014-6-9 下午5:55:56
	 * @author        :  huangszh
	 */
	public void setPraiseNum() {
		for (int i = 0; i < mHolderList.size(); i++) {
			PictureHolderForWeibo holder = mHolderList.get(i);
			if (null != holder && null != holder.rightBtn) {
				if (isPraised) {
					holder.rightBtn.setCompoundDrawablesWithIntrinsicBounds(
							R.drawable.praise_press, 0, 0, 0);
				} else {
					holder.rightBtn.setCompoundDrawablesWithIntrinsicBounds(
							R.drawable.praise_normal, 0, 0, 0);
				}
				((TextView) holder.rightBtn).setText(String
						.valueOf(praises));
			}
		}
	}

	@Override
	public View instantiateItem(ViewGroup container, int position) {
		View view = getItemView();
		bindData(position,(PictureHolderForWeibo) view.getTag());
		container.addView(view, LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT);

		return view;
	}
	/**
	 * 数据和控件绑定
	 * 
	 * <br>Created 2014-5-28 下午2:22:49
	 * @param pos 指示数据的索引
	 * @param holder 控件
	 * @author       chenqian
	 */
	private void bindData(int pos, PictureHolderForWeibo holder){
		if(null == holder){
			return;
		}
		final Image img = (Image) getItem(pos);	
		holder.pos = pos;
		if (!isLocalImage) {
			// 网络图片用centerCrop模式
			holder.ivPicture.setScaleType(ImageView.ScaleType.CENTER_CROP);
		} else {
			// 本地图片用fitCenter模式
			holder.ivPicture.setScaleType(ImageView.ScaleType.FIT_CENTER);
		}		
		setBtnIconAndEvent(holder.leftBtn,mleftBtnResId,mLeftBtnListener);
		mRightBtnListener = new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				doSave(img.image_original, img.image_ext);				
			}
		};
		setBtnIconAndEvent(holder.rightBtn,mRightBtnResId,mRightBtnListener);
		holder.image_ext = img.image_ext;
		if (isCanPraised) {// 如果是发送成功的微博界面点进来
			holder.rightBtn.setText(String.valueOf(praises));
			if (isPraised) {
				holder.rightBtn.setCompoundDrawablesWithIntrinsicBounds(
						R.drawable.praise_press, 0, 0, 0);
			} else {
				holder.rightBtn.setCompoundDrawablesWithIntrinsicBounds(
						R.drawable.praise_normal, 0, 0, 0);
			}
			holder.isLocalUrl = false;
		} else {// 如果是未发送成功的微博大图浏览
			holder.isLocalUrl = true;
		}
		holder.showImage(img.image_thumb, img.image_original,
				GlobalSetting.getWeiboNoCacheOpt(mContext));
		if (holder.isGif()) {// 如果是GIF，使用GIF控件响应关闭的事件
			holder.gifPicture.setOnClickListener(this);
		}
	}
	/**
	 * 初始化每个item的视图控件
	 * 
	 * <br>Created 2014-5-28 下午2:20:00
	 * @return 每个item的视图控件
	 * @author       chenqian
	 */
	private View getItemView(){
		View view = View.inflate(mContext, R.layout.fragment_picture_flow_item,
				null);
		view.findViewById(R.id.fragment_pic_layout).setOnClickListener(this);
		final PictureHolderForWeibo holder = new PictureHolderForWeibo();		
		holder.rlProgress = (RelativeLayout) view.findViewById(R.id.rlProgress);
		holder.cpProgress = (CircleProgress) view.findViewById(R.id.cpProgress);
		holder.ivPicture = (PhotoView) view.findViewById(R.id.ivPicture);
		holder.gifPicture = (GifImageView) view.findViewById(R.id.gifPicture);
		holder.leftBtn = (Button)view.findViewById(R.id.leftBtn);
		holder.rightBtn = (Button)view.findViewById(R.id.rightBtn);
		view.setTag(holder);
		mHolderList.add(holder);
		return view;
	}

	@Override
	public void destroyItem(ViewGroup container, int position, Object object) {
		if (object instanceof View) {
			View v = (View) object;
			if (v.getTag() instanceof PictureHolderForWeibo) {
				// 停止GIF线程
				((PictureHolderForWeibo) v.getTag()).gifPicture.quit();
			}
			mHolderList.remove(v.getTag());
			container.removeView(v);
		}
	}

	@Override
	public int getItemPosition(Object object) {
		return POSITION_NONE;
	}

	@Override
	public boolean isViewFromObject(View view, Object object) {
		return view == object;
	}

	/**
	 * 保存
	 * 
	 * <br>Created 2014-6-9 下午5:56:05
	 * @param sourceUrl url
	 * @param imageExt 图片扩展名
	 * @author        :  chenqian
	 */
	public void doSave(String sourceUrl, String imageExt) {
		new SaveTweetImageTask(sourceUrl, imageExt, mContext,
				GlobalSetting.getWeiboNoCacheOpt(mContext)).execute();

	}

	/**
	 * 喜欢
	 * 
	 * <br>Created 2014-6-9 下午5:56:35
	 * @param v view
	 * @author        :  chenqian
	 */
//	private void doLike(View v) {
//		int actionType;
//		if (mTopic.praised) {
//			mTopic.praised = false;
//			// ((Button) v).setCompoundDrawablesWithIntrinsicBounds(
//			// R.drawable.praise_normal, 0, 0, 0);
//			mTopic.praises = mTopic.praises - 1;
//			// ((TextView) v).setText(String.valueOf(mTweet.attitudesCount));
//			actionType = LikeAsyncTask.ACTION_UNLIKE;
//		} else {
//			mTopic.praised = true;
//			// ((Button) v).setCompoundDrawablesWithIntrinsicBounds(
//			// R.drawable.praise_press, 0, 0, 0);
//			mTopic.praises = mTopic.praises + 1;
//			// ((TextView) v).setText(String.valueOf(mTweet.attitudesCount));
//			actionType = LikeAsyncTask.ACTION_LIKE;
//		}
//		setPraiseNum();
//		// 防止快速点击一直启线程
//		if (mLikeTask == null || mLikeTask.getStatus() != Status.RUNNING) {
//			mLikeTask = new LikeAsyncTask(mTopic, actionType, mContext,
//					mHandler);
//			mLikeTask.execute();
//		}
//
//		Intent message = new Intent(IntentActionConst.BROADCAST_LIKE_EVENT);
//		// Add data
//		message.putExtra("id", mTopic.tid);
//		message.putExtra("like", mTopic.praised);
//		LocalBroadcastManager.getInstance(mContext).sendBroadcast(message);
//
//	}

//	// 接收task里新new的task对象，进行task状态判断
//	private Handler mHandler = new Handler() {
//		public void handleMessage(Message msg) {
//			mLikeTask = (LikeAsyncTask) msg.obj;
//		};
//	};

	/**
	 * 是否已经喜欢
	 * 
	 * <br>Created 2014-6-9 下午5:57:01
	 * @return boolean
	 * @author    :  chenqian
	 */
	public boolean isTweetLike() {
		return isPraised;
	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		if (id == R.id.gifPicture || id == R.id.fragment_pic_layout) {
			if (mContext instanceof Activity) {
				((Activity) mContext).finish();
			}
		}
	}

	/**
	 * 退出界面时一定要停止GIF线程
	 * 
	 * @n<b>函数名称</b> :Destroy
	 * @brief
	 * @see
	 * @since Ver 1.1
	 * @param
	 * @<b>作者</b> : 黄永鑫
	 * @<b>创建时间</b> : 2013-12-20上午11:52:36
	 */
	public void Destroy() {
		for (PictureHolderForWeibo holder : mHolderList) {
			holder.gifPicture.quit();
			holder.gifPicture.recycle();
		}
	}
	/**
	 * 设置左边按钮的图片id
	 * 
	 * <br>Created 2014-5-28 上午10:39:53
	 * @param resId 图片资源id
	 * @author       chenqian
	 */
	public void setLeftBtnIcon(int resId){
		mleftBtnResId = resId;
	}
	/**
	 * 设置右边按钮的图片id
	 * 
	 * <br>Created 2014-5-28 上午10:39:53
	 * @param resId 图片资源id
	 * @author       chenqian
	 */
	public void setRightBtnIcon(int resId){		
		mRightBtnResId = resId;
	}
	/**
	 * 设置按钮的图片
	 * 
	 * <br>Created 2014-5-28 上午10:48:34
	 * @param btn 按钮
	 * @param resId 图片资源id
	 * @param listener 监听器
	 * @author       chenqian
	 */
	private void setBtnIconAndEvent(Button btn, int resId, OnClickListener listener){
		if(null == btn){
			return;
		}
		if(resId > 0){
			btn.setCompoundDrawablesWithIntrinsicBounds(resId, 0, 0, 0);
			btn.setOnClickListener(listener);
		}else{
			btn.setVisibility(View.GONE);
		}
	}
	/**
	 * 设置左边按钮监听事件
	 * 
	 * <br>Created 2014-5-28 上午10:54:48
	 * @param listener 按钮监听事件
	 * @author       chenqian
	 */
	public void setLeftBtnClickListener(OnClickListener listener){
		mLeftBtnListener = listener;
	}
	/**
	 * 设置右边按钮监听事件
	 * 
	 * <br>Created 2014-5-28 上午10:54:48
	 * @param listener 按钮监听事件
	 * @author       chenqian
	 */
	public void setRightBtnClickLinstener(OnClickListener listener){
		mRightBtnListener = listener;
	}
}
